package com.zcp.todayheadline.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.github.lianghanzhen.LazyFragmentPagerAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zcp.todayheadline.ContentActivity;
import com.zcp.todayheadline.R;
import com.zcp.todayheadline.adapter.MyBase;
import com.zcp.todayheadline.bean.NewsSummary;
import com.zcp.todayheadline.view.XListView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@ContentView(R.layout.fragment_info)
public class InfoFragment extends Fragment implements XListView.IXListViewListener, LazyFragmentPagerAdapter.Laziable {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    @ViewInject(R.id.xlv)
    XListView xlv;

    boolean inject = false;
    int index = 0;


    private static InfoFragment info;
    public static List<NewsSummary> list = new ArrayList<>();
    ;
    private MyBase base;
    private Callback.Cancelable cancelable;

    public InfoFragment() {
        // Required empty public constructor
    }


    public static InfoFragment newInstance(String param1, String param2) {
        InfoFragment fragment = new InfoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        inject = true;
        View view = x.view().inject(this, inflater, container);

        xlv.setPullRefreshEnable(true);
        xlv.setPullLoadEnable(true);
        xlv.setXListViewListener(this);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!inject) {
            x.view().inject(this, this.getView());
        }

        onRefresh();

        //点击显示新闻内容
        xlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), ContentActivity.class);
                intent.putExtra("url", list.get(position - 1).url_3w);
                startActivity(intent);
            }
        });
    }

    public RequestParams getUrl(String type, String id, int pageIndex) {
        String url = String.format("http://c.m.163.com/nc/article/%1$s/%2$s/%3$s-20.html", type, id, pageIndex);
        return new RequestParams(url);
    }

    public void getNewList(String type, final String id, int pageIndex) {
        RequestParams params = getUrl(type, id, pageIndex);

        //请求数据
        //设置适配器
        cancelable = x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                List<NewsSummary> arr = parseData(result, id);
                list.addAll(arr);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                if (index == 0) {
                    //设置适配器
                    base = new MyBase(getActivity(), list);
                    xlv.setAdapter(base);
                } else {
                    base.notifyDataSetChanged();
                }
            }
        });
    }


    //解析数据
    private List<NewsSummary> parseData(String result, String id) {
        Map<String, List<NewsSummary>> map = new Gson().fromJson(result, new TypeToken<Map<String, List<NewsSummary>>>() {
        }.getType());
        List<NewsSummary> list = map.get(id);//新闻列表
        return list;
    }

    //刷新
    @Override
    public void onRefresh() {
        index = 0;
        list.clear();
        getNewList("headline", mParam2, index);
        xlv.stopLoadMore();
        xlv.stopRefresh();
        xlv.setRefreshTime("松开推荐");
    }

    //加载更多
    @Override
    public void onLoadMore() {
        index = index + 20;
        getNewList("headline", mParam2, index);
        xlv.stopLoadMore();
        xlv.stopRefresh();
        xlv.setRefreshTime("推荐中");
    }

    @Override
    public void onPause() {
        super.onPause();
        if (cancelable != null) {//取消请求
            cancelable.cancel();
        }
    }

}
